package com.kc.data.common.base;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.stream.IntStream;

/**
 * @author gc
 * @date 2020/9/15 10:13
 */
@Component
public class Md5Util {
    /***
     * MD5加码 生成32位md5码
     */
    public String string2Md5(String inStr){
        MessageDigest md5 ;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        IntStream.range(0, charArray.length).forEach(i -> byteArray[i] = (byte) charArray[i]);
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     */
    public String convertMd5(String inStr){

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++){
            a[i] = (char) (a[i] ^ 't');
        }
        return new String(a);
    }

    /**
     * Md5解密 ，两次加密操作
     * @param inStr 入参字符串
     * @return deCode
     */
    public String disConvertMd5(String inStr){
        return convertMd5(convertMd5(inStr));
    }
}
